// inputhandler.cpp
#include "inputhandler.h"
#include <QKeyEvent>
#include <QDebug>

// 修改 inputhandler.cpp 的构造函数
InputHandler::InputHandler(QWidget *targetWidget, QObject *parent) : QObject(parent) {
    targetWidget->installEventFilter(this);  // 直接调用，不赋值
    m_enabled = true;
    qDebug() << "事件过滤器已尝试安装到目标窗口";  // 仅提示尝试安装
}

bool InputHandler::eventFilter(QObject *obj, QEvent *event) {
    if (!m_enabled || event->type() != QEvent::KeyPress) {
        return QObject::eventFilter(obj, event);
    }

    QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);

    // 添加日志：打印按下的键
    qDebug() << "按下了键：" << keyEvent->key() << "（" << keyEvent->text() << "）";

    switch (keyEvent->key()) {
        case Qt::Key_Up:
        case Qt::Key_W:
            emit moveRequested(Direction::Up);
            return true;
        case Qt::Key_Down:
        case Qt::Key_S:
            emit moveRequested(Direction::Down);
            return true;
        case Qt::Key_Left:
        case Qt::Key_A:
            emit moveRequested(Direction::Left);
            return true;
        case Qt::Key_Right:
        case Qt::Key_D:
            emit moveRequested(Direction::Right);
            return true;
        case Qt::Key_R:
            emit resetRequested();
            return true;
        case Qt::Key_P:
            emit prevLevelRequested();
            return true;
        case Qt::Key_N:
            emit nextLevelRequested();
            return true;
        default:
            return QObject::eventFilter(obj, event);
    }
}
